package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.domain.UserGoods;
import cn.wolfcode.trip.base.mapper.IntegralMapper;
import cn.wolfcode.trip.base.mapper.UserGoodsMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.IUserGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserGoodsServiceImpl implements IUserGoodsService {

    @Autowired
    private UserGoodsMapper userGoodsMapper;
    @Autowired
    private IntegralMapper integralMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void insert(UserGoods userGoods) {
        UserGoods userGoods1 = (UserGoods) userGoodsMapper.selectByStoreId(userGoods.getStore().getId(),userGoods.getUser().getId());
            if (userGoods1 == null) {
                userGoodsMapper.insert(userGoods);
            }else if (userGoods1.getUser().getId()!=userGoods.getUser().getId()){
                userGoodsMapper.insert(userGoods);
            }else if (userGoods1.getState()==1){
                userGoodsMapper.updateNumber(userGoods.getNumber(), userGoods1.getId());
            }else if (userGoods1.getState()==2||userGoods1.getState()==3){
                userGoodsMapper.insert(userGoods);
            }
        }


    @Override
    public List<UserGoods> listByUserId(UserGoods userGoods) {
        return userGoodsMapper.listByUserId(userGoods);
    }

    @Override
    public void delete(UserGoods userGoods) {
        userGoodsMapper.deleteByPrimaryKey(userGoods.getId());
    }

    @Override
    public void buyStore(UserGoods userGoods, int integral) {
        //结算
        userGoodsMapper.update(userGoods);
        //扣除积分
        integralMapper.updateIntegral(integral,userGoods.getUser().getId());
    }

    @Override
    public List<UserGoods> selectBuyStore(UserGoods userGoods) {

        return userGoodsMapper.selectBuyStore(userGoods);
    }

    @Override
    public void checkPassword(String password, Long uid) {
       User user=userMapper.checkPassword(password, uid);
        if (user==null){
             throw new RuntimeException("密码错误");
         }
    }
}
